/*
 * *
 *  * blog.coder4j.cn
 *  * Copyright (C) 2016-2019 All Rights Reserved.
 *
 */
package com.im.socket;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.im.redis.AppMessage;
import com.im.util.SessionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.List;

/**
 * @author buhao
 * @version MyWSHandler.java, v 0.1 2019-10-17 17:10 buhao
 */
@Slf4j
@Component
public class HttpAuthHandler extends TextWebSocketHandler {
    @Autowired
    private AppMessage appMessage;
    /**
     * socket 建立成功事件
     *
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        String id = session.getAttributes().get("id").toString();
        if (id != null) {
            // 用户连接成功，放入在线用户缓存
            SessionUtil.put(id, session);
            log.error("在线用户数：" + SessionUtil.size());
            //查询是否有未读消息
            List<String> readMsg = SessionUtil.getReadMsg(id);
            if(null != readMsg && readMsg.size() >0){
                readMsg.forEach(x->{
                    try {
                        session.sendMessage(new TextMessage(x));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
            }
        } else {
            throw new RuntimeException("用户登录已经失效!");
        }
    }

    /**
     * 接收消息事件 消息转对象根据某个字段处理业务
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 获得客户端传来的消息
        String payload = message.getPayload();
        JSONObject obj = JSONUtil.parseObj(payload);
        Object mechod = obj.get("cmd");
        //反射执行
        ReflectUtil.invoke(appMessage, mechod.toString(), message.getPayload(), session);
    }

    /**
     * socket 断开连接时
     *
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        Object id = session.getAttributes().get("id");
        if (id != null) {
            log.error(id + " 退出链接！");
            // 用户退出，移除缓存
            SessionUtil.remove(id.toString());
        }
    }

}
